package com.hebtu.helper.modules.sys.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hebtu.helper.common.utils.LayuiPage;
import com.hebtu.helper.common.utils.Query;
import com.hebtu.helper.modules.sys.service.SysRoleMenuService;
import com.hebtu.helper.modules.sys.service.SysRoleService;
import com.hebtu.helper.modules.sys.dao.SysRoleDao;
import com.hebtu.helper.modules.sys.entity.SysRoleEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 分页
     * @param params
     * @return
     */
    @Override
    public LayuiPage queryPage(Map<String, Object> params) {
        String roleName = (String) params.get("roleName");
        Page<SysRoleEntity> page = this.selectPage(
                new Query<SysRoleEntity>(params).getPage(),
                new EntityWrapper<SysRoleEntity>()
                        .like(StringUtils.isNotBlank(roleName),"role_name", roleName)
        );
        return new LayuiPage(page.getRecords(), page.getTotal());
    }

    /**
     * 保存角色及角色对应的菜单
     * 1.保存角色基本信息
     * 2.保存角色对应的菜单信息
     * @param sysRoleEntity
     */
    @Override
    public boolean save(SysRoleEntity sysRoleEntity) {
        Integer i=baseMapper.insert(sysRoleEntity);
        boolean rmsave=sysRoleMenuService.save(sysRoleEntity.getRoleId(), sysRoleEntity.getMenuId());
        if(i>0 && rmsave)
            return true;
        return false;
    }

    /**
     * 删除
     * 1.删除角色对应菜单
     * 2.删除角色id
     * @param roleId
     * @return
     */
    @Override
    public boolean delete(Long roleId) {
        if(baseMapper.deleteById(roleId)>0 && sysRoleMenuService.deleteByRoleId(roleId))
            return true;
        return false;
    }

    /**
     * 修改
     * 1.先删除原来对应的菜单Id
     * 2.新增新的菜单
     * @param sysRoleEntity
     * @return
     */
    @Override
    public void update(SysRoleEntity sysRoleEntity) {
        sysRoleMenuService.deleteByRoleId(sysRoleEntity.getRoleId());
        sysRoleMenuService.save(sysRoleEntity.getRoleId(), sysRoleEntity.getMenuId());
    }

    /**
     * 查询
     * 1.先查询基础角色
     * 2.查询角色对应的菜单
     * @param roleId
     * @return
     */
    @Override
    public SysRoleEntity queryByRoleId(Long roleId) {
        SysRoleEntity sysRoleEntity = baseMapper.selectById(roleId);
        List<Long> listRole = new ArrayList<>();
        listRole.add(roleId);
        sysRoleEntity.setMenuId(sysRoleMenuService.queryMenuIdByRoleId(listRole));
        return sysRoleEntity;
    }

}
